import { Component, OnInit } from '@angular/core'
import { JsonApiService } from '../core/api/json-api.service'
import { Router } from '@angular/router'
import { widgetDatas, WidgetKey, WidgetProps } from './widget/model'

export interface WidgetListProps extends WidgetProps {
  key: WidgetKey
  used: boolean // 是否被使用
}

export interface GridProps {
  layout: number[]
  componentList: Array<WidgetKey[]>
}

const defaultGrid: GridProps = {
  //默认分栏数量和宽度 例如 [12,6,6] [24,16,8] [6,6,6,6,16,8,24]
  layout: [6, 6, 6, 6, 16, 8, 24],
  // componentList: [['welcome'], ['version'], ['time', 'progress']] // echarts
  componentList: [[], [], [], [], [], [], []]
}
@Component({
  selector: 'home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
  allWidget = widgetDatas //所有已声明的组件属性
  customizing = false // 自定义布局状态
  isCompsEmpty = false // 是否有展示的组件
  currentActiveIndex = -1 // 当前激活的分栏位置
  grid: GridProps // 模版分栏及每个分栏对应的模版名称
  myWidgetList: WidgetListProps[] = [] // 没有被使用的组件列表
  componentsConfig = {} // 组件常用项目Id
  roleComponents: WidgetKey[] = [] // 用户拥有的组件列表

  constructor(private jsonApiService: JsonApiService, private router: Router) {}

  // 只调用一次，用于初始化组件
  ngOnInit() {
    console.log('ngOnInit')
    this.fetchData()
  }

  // 在组件以及其子组件初始化完成后会被调用
  ngAfterViewInit() {
    console.log('ngAfterViewInit')
  }

  // 在组件销毁之前调用，进行一些清理工作
  ngOnDestroy() {
    console.log('ngOnDestroy')
  }

  //获取接口初始值
  fetchData() {
    const that = this
    this.jsonApiService.http_get('control/station/config/queryAllComponent.html', false).subscribe(data => {
      if (data.success) {
        const result = data.data.userComponent || {}
        that.grid = result.components ? JSON.parse(result.components) : defaultGrid
        const componentsConfig = result.componentsConfig || []
        for (const item of componentsConfig) {
          this.componentsConfig[item.componentCode] = item.companyIds || ''
        }
        this.roleComponents = data.data.roleComponent || []
        that.initData()
        // setStorage('_old_grid_', this.grid)
      }
    })
  }

  initData() {
    this.isCompsEmpty = this.getUsedWidgets().length <= 0
    this.myWidgetList = this.getWidgetList().filter(item => !item.used)
  }

  /**
   * 获取已展示的组件列表
   */
  getUsedWidgets() {
    return this.grid.componentList.reduce((a, b) => a.concat(b))
  }

  /**
   * 获取所有的组件列表（如果已经使用则打上标记）
   */
  getWidgetList() {
    const list: WidgetListProps[] = []
    const keys = this.roleComponents
    for (const key of keys) {
      let isUse = false
      if (this.getUsedWidgets().includes(key)) {
        isUse = true
      }
      list.push({ ...this.allWidget[key], key, used: isUse })
    }
    return list
  }

  /**
   * 设置分栏排列
   * @param layout [12,6,6] [24,16,8] [6,6,6,6,16,8,24]
   */
  setLayout(layout: number[]) {
    this.grid.layout = [...layout]
  }

  /**
   * 当前激活的视图位置
   */
  activeView(index: number) {
    console.log('activeView', index)
    this.currentActiveIndex = index
  }

  /**
   * 删除组件
   */
  remove(component: string) {
    this.grid.componentList.forEach((array, index) => {
      const newArray = array.filter(item => item != component)
      this.grid.componentList[index] = newArray
    })
    this.initData()
  }

  /**
   * 添加组件
   */
  push(item: WidgetListProps) {
    if (this.currentActiveIndex === -1) {
      this.jsonApiService.message('请先选择对应添加区域后再添加组件！')
      return
    }
    this.grid.componentList[this.currentActiveIndex].push(item.key)
    this.initData()
  }

  /**
   * 保存模版排列
   */
  save() {
    //调用接口
    const list = this.grid.componentList.toString().split(',')
    if (list.length > 10) {
      this.jsonApiService.message('最多添加10个部件，请减少部件后保存')
      return
    }
    this.close()
    const postParam = new FormData()
    postParam.append('components', JSON.stringify(this.grid)) //固件key名称
    this.jsonApiService.form_http('control/station/config/addControlStationConfig.html', postParam).subscribe(data => {
      this.jsonApiService.message(data.message)
      // if (data.success) {
      // setStorage('_old_grid_', this.grid)
      // }
    })
  }

  /**
   * 开启自定义模版
   */
  async custom() {
    this.customizing = true
    const oldWidth = $('#widgetsRef').outerWidth(false) // 返回元素的宽度（包括元素宽度、内边距和边框，不包括外边距）
    console.log(oldWidth)
    await sleep(0) // 等待 0ms 类似 nextTick 作用让界面先更新再进行动画
    const scale = $('#widgetsRef').outerWidth(false) / oldWidth
    $('#widgetsRef').css('transform', `scale(${scale})`)
  }

  /**
   * 关闭自定义模版
   */
  close() {
    this.customizing = false
    this.currentActiveIndex = -1
    $('#widgetsRef').css('transform', '')
  }

  /**
   * 恢复初始排版
   */
  backDefault() {
    this.close()
    this.grid = defaultGrid
    // remove('_old_grid_')
  }
}

function sleep(delay = 1000) {
  return new Promise(resolve => setTimeout(resolve, delay))
}

const cache: Record<string, any> = {}

function getStorage(key: string, defaultReturn: any = '') {
  if (!cache[key]) {
    const res = localStorage.getItem(key)
    if (res == null) {
      return defaultReturn
    }
    cache[key] = res
  }
  try {
    return JSON.parse(cache[key])
  } catch (err) {
    return cache[key]
  }
}

function setStorage(key: string, val: any) {
  if (typeof val === 'object') {
    val = JSON.stringify(val)
  }
  localStorage.setItem(key, val)
  cache[key] = val
}

function remove(key: string) {
  localStorage.removeItem(key)
  if (cache[key]) {
    cache[key] = ''
  }
}
